package Controller;

import Model.AIPlayer;
import Model.Board;
import Model.HumanPlayer;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ButtonController implements ActionListener {

    //读取GameView中的棋盘 按钮
    private JButton[] jb;
    public void setButtons(JButton[] buttons){
        this.jb = buttons;
    }

    //读取Board,需要每次点击按钮后 更新 board中棋盘的数据
    private Board board;
    public void setBoard(Board board){
        this.board = board;
    }

    //读取 游戏模式
    private int gamemodel;
    public void setGamemodel(int i){
        this.gamemodel = i;
    }

    //需要GameController中的 游戏结束 操作
    private GameController gameController;
    public void setGameController(GameController gameController){
        this.gameController = gameController;
    }

    //人机交互模式，读取ai玩家
    private AIPlayer ai;
    public void setAIPlayer(AIPlayer ai){
        this.ai = ai;
    }
    //人机交互模式，读取人类玩家
    private HumanPlayer human;
    public void setHumanPlayer(HumanPlayer human){
        this.human = human;
    }

    //初始化 双人对战 模式的 交替执行
    private boolean flag = true;

    @Override
    public void actionPerformed(ActionEvent e) {

        for (int i = 0; i < 9; i++) {
            if (e.getSource() == jb[i]){

                //双人对战模式的 处理逻辑
                if (gamemodel == 0){

                    if (flag){
                        jb[i].setText("X");
                        flag = false;
                    }else {
                        jb[i].setText("O");
                        flag = true;
                    }

                    //更新棋盘数据
                    board.setState(i,jb[i].getText());
                    //点击过的按钮 不可再点
                    jb[i].setEnabled(false);

                }
                //人机交互模式的 处理逻辑
                else if (gamemodel == 1) {

                    jb[i].setText(human.getName());
                    jb[i].setEnabled(false);
                    board.setState(i,jb[i].getText());

                    if (board.Judge() == 1){
                        //ai下棋操作
                        int next = ai.minimax(board.getState());

                        jb[next].setText(ai.getName());
                        jb[next].setEnabled(false);
                        board.setState(next,jb[next].getText());
                    }

                }

            }

        }

        //每次点击按钮后都会判断游戏是否结束
        int result = board.Judge();
        if (result == board.getWin() || result == board.getLose() || result == board.getDraw()) {
            gameController.gamerover();
        }

    }
}